import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/public/flutter_sound_player.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';
import 'package:namewava/jc_rote_path.dart';
import 'package:namewava/pages/mine/widgets/jc_pop.dart';
import 'package:namewava/pages/mine/widgets/jc_record.dart';
import 'package:namewava/utils/jc_cache.dart';
import 'package:namewava/utils/jc_global.dart';
import 'package:namewava/utils/jc_image_path.dart';
import 'package:namewava/utils/jc_screenutil_info.dart';
import 'package:namewava/utils/jc_text_style.dart';
import 'package:namewava/utils/js_request.dart';
import 'package:notification_centre/notification_centre.dart';
import 'package:svgaplayer_flutter/svgaplayer_flutter.dart';

class JcMine extends StatefulWidget {
  const JcMine({super.key});

  @override
  State<JcMine> createState() => _JcMineState();
}

class _JcMineState extends State<JcMine> with AutomaticKeepAliveClientMixin {
  List meuns = [
    {
      'image': JcImagePath.jcMineItemBg,
      'name': 'Compiler',
      'path': JcRotePath.jcMineInfo
    },
    {
      'image': JcImagePath.jcMineItemBg,
      'name': 'About',
      'path': JcRotePath.jcAbout
    },
    {
      'image': JcImagePath.jcMineItemBg,
      'name': 'Setting',
      'path': JcRotePath.jcSet
    },
    {
      'image': JcImagePath.jcMineItemBg,
      'name': 'Log out of account',
      'path': ''
    }
  ];

  RxString userAvater = ''.obs;
  RxInt myCoins = 0.obs;
  RxString nickname = ''.obs;
  RxString myId = ''.obs;
  RxString t = ''.obs;
  RxInt recorderTap = 0.obs;

  FlutterSoundPlayer? _soundPlayer = FlutterSoundPlayer();
  RxBool isPlayerRecorder = false.obs;
  RxInt recorderTime = 0.obs;
  RxString listen = JcImagePath.jcWavaSoundListen.obs;
  RxBool _isFirstRegister = false.obs;
  String _recorderPath = '';
  RxString deleteIcon = JcImagePath.jcWavaDeleteRecorder.obs;
  _wavaUserInfo() {
    JsRequest.getWavaUserInfo(success: (res) {
      userAvater.value = res['avatarThumbUrl'];
      myCoins.value = res['availableCoins'];
      nickname.value = res['nickname'];
      String userId = res['userId'].toString();
      t.value = userId;
      userId = userId.substring(0, 6);
      myId.value = userId;
    });
  }

  _getFirstRegister() {
    var isFirstRegister = JcCache.getInstance().get('isFirstRegister');
    if (isFirstRegister is bool && isFirstRegister) {
      _isFirstRegister.value = true;
    } else {
      _isFirstRegister.value = false;
    }
  }

  @override
  void initState() {
    super.initState();
    print('JcMine-initState');
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getFirstRegister();
      _wavaUserInfo();
    });
    NotificationCenter().addObserver('wavaLoninEvents', this, (r) {
      if (mounted) {
        _getFirstRegister();
        _wavaUserInfo();
      }
    });

    NotificationCenter().addObserver('wavaFixUserInfo', this, (r) {
      if (mounted) {
        _wavaUserInfo();
      }
    });

    NotificationCenter().addObserver('wavaFixUserAvatar', this, (r) {
      if (mounted) {
        _isFirstRegister.value = false;
        userAvater.value = r['url'];
        // _wavaUserInfo();
      }
    });
    NotificationCenter().addObserver('coinChange', this, (res) {
      if (mounted) {
        _wavaUserInfo();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    NotificationCenter().removeObserver('wavaLoninEvents', this);
    NotificationCenter().removeObserver('wavaFixUserInfo', this);
    NotificationCenter().removeObserver('wavaFixUserAvatar', this);
    NotificationCenter().removeObserver('coinChange', this);
    _soundPlayer?.closePlayer();
    _soundPlayer = null;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: null,
      body: _mineWidget(),
    );
  }

  _mineWidget() {
    return Container(
      height: JcScreenutilInfo.screenHeight,
      width: JcScreenutilInfo.screenWidth,
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage(JcImagePath.jcMineBg), fit: BoxFit.fill)),
      child: Column(
        children: [
          Container(
            // margin: EdgeInsets.only(top: JcScreenutilInfo.statusBarHeight),
            margin: const EdgeInsets.only(top: 44),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  alignment: Alignment.topLeft,
                  // color: Colors.red,
                  width: 0.5 * (JcScreenutilInfo.screenWidth - 145.w),
                  child: GestureDetector(
                    child: Container(
                      margin: EdgeInsets.only(left: 24.w, top: 15.h),
                      padding: EdgeInsets.only(left: 9.w, right: 5.w),
                      width: 80.w,
                      height: 26.w,

                      /// constraints: BoxConstraints(minHeight: 26.w,minWidth: 60.w),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(13.w)),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        //  mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                            JcImagePath.jcMineZs,
                            width: 22.w,
                            height: 22.w,
                          ),
                          SizedBox(
                            width: 5.w,
                          ),
                          Obx(() {
                            return Text(
                              myCoins.value.toString(),
                              style:
                                  JcTextStyle.octoberDevanagariMediumTextStyle(
                                      13.sp, const Color(0xFF00346D)),
                            );
                          })
                        ],
                      ),
                    ),
                    onTap: () {
                      JcGlobal.of(context).logReport({'page': 'purchase'});
                      Get.toNamed(JcRotePath.jcPurchase);
                    },
                  ),
                ),
                GestureDetector(
                  child: Container(
                    height: 145.w,
                    width: 145.w,
                    alignment: Alignment.center,
                    decoration: const BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage(JcImagePath.jcMineHeadBg),
                            fit: BoxFit.fill)),
                    child: Container(
                      height: 100.w,
                      width: 100.w,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50.w),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.w),
                        child: Obx(() {
                          if (_isFirstRegister.value) {
                            return Image.asset(
                              JcImagePath.jcWavaDfuHeadIcon,
                              width: double.infinity,
                              height: double.infinity,
                              fit: BoxFit.fill,
                            );
                          }

                          if (userAvater.value == '') {
                            return const SizedBox(
                              width: 10,
                            );
                          }

                          return FadeInImage.assetNetwork(
                            placeholder: JcImagePath.jcWavaDfuHeadIcon,
                            image: userAvater.value,
                            width: double.infinity,
                            height: double.infinity,
                          );
                        }),
                      ),
                    ),
                  ),
                  onTap: () {
                    Get.toNamed(JcRotePath.jcMineInfo);
                  },
                )
              ],
            ),
          ),
          // Container(
          //   width: 0.5 * (JcScreenutilInfo.screenWidth - 145.w),
          // )
          _contentWidget()
        ],
      ),
    );
  }

  _contentWidget() {
    return Expanded(
        child: Container(
      margin: EdgeInsets.only(top: 34.h),
      child: SingleChildScrollView(
        child: Column(
          children: [
            _infoWidget(),
            Column(
              children: _minesWidget(),
            )
          ],
        ),
      ),
    ));
  }

  _infoWidget() {
    return Container(
      margin: EdgeInsets.only(left: 24.w, right: 24.w),
      height: 184.h,
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage(JcImagePath.jcMineInfoBg), fit: BoxFit.fill)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Obx(() {
            return _infoItem(nickname.value, 0);
          }),
          Obx(() {
            return _infoItem('ID ${t.value}', 1);
          }),
          _infoItem('Phonetics：', 2)
        ],
      ),
    );
  }

  List<Widget> _minesWidget() {
    List<Widget> mm = [];
    mm.add(SizedBox(
      height: 20.h,
    ));
    for (var element in meuns) {
      mm.add(_mineItem(element));
    }
    mm.add(SizedBox(
      height: 100.h,
    ));

    return mm;
  }

  _mineItem(Map info) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(left: 24.w, right: 24.w, bottom: 12.h),
        height: 53.h,
        padding: EdgeInsets.only(left: 45.w, right: 40.w),
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(info['image']), fit: BoxFit.fill)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              info['name'],
              style: JcTextStyle.sourceKeynoteartHansTextStyle(
                  16.sp, Colors.white),
            ),
            Icon(
              Icons.arrow_forward,
              color: Colors.white,
              size: 30.sp,
            )
          ],
        ),
      ),
      onTap: () {
        String path = info['path'];
        if (path != '') {
          Get.toNamed(path, arguments: {'userId': t.value});
        } else {
          Get.dialog(
              JcPop(
                  btnTitles: const ['Log out of account'],
                  cancelTitle: "Cancel",
                  tapEvents: (index) {
                    JcGlobal.of(context).logReport({'page': 'logout'});
                    JsRequest.logoutRequest(success: (res) {
                      JcCache.getInstance().setData('wavaIsLogin', false);
                      Get.toNamed(JcRotePath.jcLogin);
                    });
                  }),
              useSafeArea: false);
        }
      },
    );
  }

  _infoItem(String title, int type) {
    return InkWell(
      child: Container(
        margin: EdgeInsets.only(left: 25.w, right: 25.w, bottom: 10.h),
        height: 36.h,
        decoration: BoxDecoration(
            color: const Color.fromRGBO(151, 180, 245, 1),
            borderRadius: BorderRadius.circular(18.h)),
        padding: EdgeInsets.only(left: 30.w, right: 30.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              title,
              style: JcTextStyle.sourceKeynoteartHansTextStyle(
                  13.sp, Colors.white),
            ),
            type == 0
                ? const SizedBox(
                    width: 0,
                  )
                : type == 1
                    ? InkWell(
                        child: Image.asset(
                          JcImagePath.jcCopycon,
                          width: 27.w,
                          height: 12.h,
                        ),
                      )
                    : Obx(() {
                        if (recorderTap.value == 0) {
                          ///正常状态
                          return InkWell(
                            child: Image.asset(
                              JcImagePath.jcMineMkf,
                              width: 11.w,
                              height: 14.h,
                            ),
                          );
                        } else {
                          if (isPlayerRecorder.value) {
                            return Container(
                              height: 20.h,
                              padding: EdgeInsets.only(
                                left: 10.w,
                              ),
                              decoration: BoxDecoration(
                                  color: const Color(0xFF1C2355),
                                  borderRadius: BorderRadius.circular(4.r)),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Obx(() {
                                    return Text(
                                      '${recorderTime.value}',
                                      style: JcTextStyle
                                          .poetsenOneRegularTextStyle(
                                              10.sp, Colors.white),
                                    );
                                  }),
                                  Obx(() {
                                    // return Text('123');
                                    return SizedBox(
                                      height: 15.h,
                                      width: 30.w,
                                      child: SVGASimpleImage(
                                        assetsName: listen.value,
                                      ),
                                    );
                                  })
                                ],
                              ),
                            );
                          } else {
                            return Row(
                              children: [
                                Container(
                                  height: 20.h,
                                  padding: EdgeInsets.only(
                                    left: 10.w,
                                  ),
                                  decoration: BoxDecoration(
                                      color: const Color(0xFF1C2355),
                                      borderRadius: BorderRadius.circular(4.r)),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Obx(() {
                                        return Text(
                                          '${recorderTime.value}',
                                          style: JcTextStyle
                                              .poetsenOneRegularTextStyle(
                                                  10.sp, Colors.white),
                                        );
                                      }),
                                      SizedBox(
                                        width: 5.w,
                                      ),
                                      Image.asset(
                                        JcImagePath.jcWavaVoiceIcon,
                                        width: 16.w,
                                        height: 16.w,
                                      ),
                                      SizedBox(
                                        width: 10.w,
                                      ),
                                    ],
                                  ),
                                ),
                                SizedBox(
                                  width: 5.w,
                                ),
                                InkWell(
                                  child: Image.asset(
                                    deleteIcon.value,
                                    width: 15.w,
                                    height: 15.w,
                                  ),
                                  onTap: () {
                                    recorderTap.value = 0;
                                    _recorderPath = '';
                                  },
                                )
                              ],
                            );
                          }
                        }
                      })
          ],
        ),
      ),
      onTap: () {
        if (type == 0) {
          // JcGlobal.of(context).baseUrl = '123';
        } else if (type == 1) {
          Clipboard.setData(ClipboardData(text: t.value));
          EasyLoading.showSuccess('Success');
        } else {
          if (recorderTap.value == 0) {
            Get.dialog(JcRecord(
              recorderDismissEvents:
                  (int recorderSeconds, String recorderPath) {
                recorderTime.value = recorderSeconds;
                // isPlayerRecorder.value = true;
                _recorderPath = recorderPath;
                recorderTap.value = 1;
              },
            ), useSafeArea: false);
          } else {
            if (isPlayerRecorder.value) {
              EasyLoading.showError('Playing');
            } else {
              _initRecorder();
            }
          }
        }
      },
    );
  }

  _initRecorder() {
    bool? isOpen = _soundPlayer?.isOpen();

    ///未打开播放器
    if (isOpen == null || isOpen == false) {
      print('打开播放');
      _soundPlayer?.openPlayer().then((value) {
        _playRecorder(_recorderPath);
      });
    } else {
      _playRecorder(_recorderPath);
    }
  }

  _playRecorder(String path) {
    isPlayerRecorder.value = true;
    _soundPlayer
        ?.startPlayer(
            fromURI: path,
            whenFinished: () {
              isPlayerRecorder.value = false;
            })
        .then((value) {});
  }

  @override
  bool get wantKeepAlive => true;
}
